package com._21cn.cms.article.web.controller;

import com._21cn.cms.article.entity.Special;
import com._21cn.cms.article.service.SpecialService;
import com._21cn.cms.common.FormSelector;
import com._21cn.cms.common.obj.ResponseObj;
import com._21cn.cms.common.utils.ResponseUtil;
import com._21cn.cms.site.entity.Channel;
import com._21cn.cms.site.entity.Config;
import com._21cn.cms.site.service.ChannelService;
import com._21cn.cms.site.service.ConfigService;
import com._21cn.cms.template.entity.Template;
import com._21cn.cms.template.entity.vo.Page;
import com._21cn.cms.template.utils.TemplateHelper;
import com._21cn.framework.base.controller.BaseController;
import com._21cn.framework.flip.PageList;
import com._21cn.framework.http.HttpRequestInfo;
import com._21cn.framework.utils.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import java.io.PrintStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping({"/admin/article/special"})
public class SpecialController extends BaseController
{
    private static String listView = "/admin/article/special/list";
    private static String showView = "/admin/article/special/show";
    private static String jsonView = "/admin/article/special/json";
    private static String formView = "/admin/article/special/form";
    private static String redirectListView = "redirect:/admin/article/special/list.do";

    private Map<String, String> propertyTitleMap = null;

    @Autowired(required=false)
    private SpecialService specialService;

    @Autowired(required=false)
    @Qualifier("specialValidator")
    private Validator specialValidator;

    @Autowired(required=false)
    private ConfigService configService;

    @Autowired(required=false)
    private ChannelService channelService;

    @Autowired
    private TemplateHelper templateHelper;
    private static Map<String, String> generalTemplateMap = new HashMap();

    @RequestMapping({"/list"})
    public String listSpecial(HttpServletRequest request, HttpServletResponse response, ModelMap model)
    {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter("view", listView);
        setRequestModelMap(request, model, true);
        return view;
    }

    @RequestMapping({"/search"})
    public String searchSpecial(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter("view", jsonView);
        setRequestModelMap(request, model, true);
        PageList result = getPageList(model);
        model.addAttribute("objListJson", JSON.toJSONString(result, new SerializerFeature[] { SerializerFeature.WriteDateUseDateFormat }));
        return view;
    }

    @RequestMapping({"/show"})
    public String showSpecial(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter("view", showView);
        Integer id = Integer.valueOf(reqInfo.getIntParameter("id", -1));
        if (id.intValue() > 0) {
            Special special = (Special)this.specialService.getById(id);
            if (special == null) {
                model.put("error.param.wrong", "无效参数");
            }

            model.addAttribute("special", special);
        }
        setRequestModelMap(request, model);
        return view;
    }

    @RequestMapping({"/edit"})
    public String editSpecial(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter("view", formView);
        Integer id = Integer.valueOf(reqInfo.getIntParameter("id", -1));
        Special special = new Special();
        if (id.intValue() > 0) {
            special = (Special)this.specialService.getById(id);
            if (special == null) {
                model.put("error.param.wrong", "无效参数");
            }
        }
        model.addAttribute("special", special);
        model.addAttribute("statusMap", FormSelector.getStatusMap());
        setRequestModelMap(request, model);
        return view;
    }

    @RequestMapping({"/save"})
    public String saveSpecial(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = Integer.valueOf(reqInfo.getIntParameter("id", -1));
        if (id.intValue() > 0) {
            Special special = (Special)this.specialService.getById(id);
            if (bind(request, special, model, new Validator[] { this.specialValidator }).hasErrors()) {
                return formView;
            }
            Date createTime = special.getCreateTime();
            Channel channel = this.channelService.getById(special.getChannelId());
            if (channel != null) {
                special.setHost(channel.getHost());
                String date = DateUtil.formatDate(createTime, "yyyyMMdd");
                String path = channel.getPath() + "/special/" + special.getCode() + "/" + date + "/index.shtml";
                special.setPath(path);
                special.setUrl("http://" + channel.getHost() + "/special/" + special.getCode() + "/" + date + "/index.shtml");
            }
            this.specialService.update(special);
        } else {
            Special special = new Special();
            if (bind(request, special, model, new Validator[] { this.specialValidator }).hasErrors()) {
                return formView;
            }
            Channel channel = this.channelService.getById(special.getChannelId());
            if (channel != null) {
                special.setHost(channel.getHost());
                String date = DateUtil.formatDate(new Date(), "yyyyMMdd");
                String path = channel.getPath() + "/special/" + special.getCode() + "/" + date + "/index.shtml";
                special.setPath(path);
                special.setUrl("http://" + channel.getHost() + "/special/" + special.getCode() + "/" + date + "/index.shtml");
            }
            this.specialService.insert(special);
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter("queryParam", "");
    }

    @RequestMapping({"/updateStatus"})
    public String updateSpecialStatus(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer status = Integer.valueOf(reqInfo.getIntParameter("status", -1));
        if (status.intValue() < 0) {
            model.clear();
            return redirectListView + "?" + reqInfo.getParameter("queryParam", "");
        }
        setRequestModelMap(request, model);
        String objectIds = getGetObjectIds(reqInfo, model);
        if (objectIds.length() > 0) {
            this.specialService.update(model);
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter("queryParam", "");
    }

    @RequestMapping({"/delete"})
    public String deleteSpecial(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap(request, model);
        String objectIds = getGetObjectIds(reqInfo, model);
        if (objectIds.length() > 0) {
            this.specialService.delete(model);
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter("queryParam", "");
    }

    @RequestMapping({"/generalTemplate"})
    public String generalTemplate(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        Map generalIdMap = getTemplateMap();
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter("view", jsonView);
        if (!view.equals(jsonView)) {
            model.addAttribute("generalIdMap", generalIdMap);
            return view;
        }
        int left_1_rc = reqInfo.getIntParameter("left_1_rc", 1);
        int right_1_rc = reqInfo.getIntParameter("right_1_rc", 1);
        int right_2_rc = reqInfo.getIntParameter("right_2_rc", 1);
        int left_2_rc = reqInfo.getIntParameter("left_2_rc", 1);

        int left_1_id = reqInfo.getIntParameter("left_1_id", 0);
        int right_1_id = reqInfo.getIntParameter("right_1_id", 0);
        int right_2_id = reqInfo.getIntParameter("right_2_id", 0);
        int left_2_id = reqInfo.getIntParameter("left_2_id", 0);

        int siteFileId = reqInfo.getIntParameter("siteFileId", 0);
        String picurl = reqInfo.getParameter("picurl", "");
        try
        {
            Config config = this.configService.getConfig(Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(0), "topic_common_template_1");
            String content = config.getValue();
            content = content.replace("##head_image_url##", picurl);
            if (left_1_rc == 2)
                content = content.replace("##left_1_data##", "#set( $articleList = $articleListLabel.column('" + left_1_id + "').hasPicture().limit(5).loadArticleExt() )");
            else {
                content = content.replace("##left_1_data##", "#set( $articleList = $articleListLabel.region('" + left_1_id + "').hasPicture().limit(5).loadArticleExt() )");
            }

            if (right_1_rc == 2)
                content = content.replace("##right_1_data##", "#set( $articleList = $articleListLabel.column('" + right_1_id + "').limit(3).loadArticleExt() )");
            else {
                content = content.replace("##right_1_data##", "#set( $articleList = $articleListLabel.region(" + right_1_id + ").limit(3).loadArticleExt() )");
            }

            if (left_2_rc == 2)
                content = content.replace("##left_2_data##", "#set( $articleList = $articleListLabel.column('" + left_2_id + "').hasPicture().limit(4).loadArticleExt() )");
            else {
                content = content.replace("##left_2_data##", "#set( $articleList = $articleListLabel.region(" + left_2_id + ").hasPicture().limit(4).loadArticleExt() )");
            }

            if (right_2_rc == 2)
                content = content.replace("##right_2_data##", "#set( $articleList = $articleListLabel.column('" + right_2_id + "').limit(10).loadArticleExt()  )");
            else {
                content = content.replace("##right_2_data##", "#set( $articleList = $articleListLabel.region(" + right_2_id + ").limit(10).loadArticleExt() )");
            }

            System.out.println(content);
            model.addAttribute("objJson", content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return view;
    }

    @RequestMapping({"/preview"})
    public void previewSpecial(HttpServletRequest request, HttpServletResponse response, ModelMap model)
    {
        ResponseObj responseObj = new ResponseObj();
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String content = reqInfo.getParameter("templateContent", "");

        String result = "";
        Template template = new Template();
        template.setId(Integer.valueOf(9999));
        template.setContent(content);
        template.setTemplateType(Integer.valueOf(5));
        try {
            Page page = new Page();
            page.setTemplate(template);
            List list = this.templateHelper.generatePage(page, true);
            result = (String)list.get(0);
            responseObj.setErrorCode(Integer.valueOf(1));
            responseObj.setMessage(result);
        } catch (Exception e) {
            responseObj.setErrorCode(Integer.valueOf(-1));
            responseObj.setMessage("模板预览失败！");
        }
        String pageContent = responseObj.getMessage();
        ResponseUtil.returnMsg(response, pageContent);
    }

    public Map<String, String> getTemplateMap()
    {
        generalTemplateMap.put("topic_common_template_1", "电脑手机通用专题模板");
        return generalTemplateMap;
    }

    private PageList<Special> getPageList(ModelMap model) {
        if (model.containsKey("likeName"))
            model.put("likeName", model.get("likeName").toString().toLowerCase());
        PageList specialList = this.specialService.getList(model, Integer.parseInt(model.get("pageNo").toString()), Integer.parseInt(model.get("pageSize").toString()));
        model.addAttribute("specialList", specialList);
        model.addAttribute("objList", specialList);
        model.addAttribute("pageTurn", specialList.getPageTurn());
        model.addAttribute("titleMap", getPropertyTitleMap());
        return specialList;
    }

    private Map<String, String> getPropertyTitleMap() {
        if (this.propertyTitleMap == null) {
            this.propertyTitleMap = new HashMap();
            this.propertyTitleMap.put("id", "id");
            this.propertyTitleMap.put("title", "title");
            this.propertyTitleMap.put("code", "code");
            this.propertyTitleMap.put("siteId", "siteId");
            this.propertyTitleMap.put("channelId", "channelId");
            this.propertyTitleMap.put("host", "host");
            this.propertyTitleMap.put("url", "url");
            this.propertyTitleMap.put("path", "path");
            this.propertyTitleMap.put("thumbPicUrl", "thumbPicUrl");
            this.propertyTitleMap.put("templateId", "templateId");
            this.propertyTitleMap.put("keyword", "keyword");
            this.propertyTitleMap.put("description", "description");
            this.propertyTitleMap.put("memo", "memo");
            this.propertyTitleMap.put("status", "status");
            this.propertyTitleMap.put("createUserId", "createUserId");
            this.propertyTitleMap.put("createTime", "createTime");
            this.propertyTitleMap.put("modifyUserId", "modifyUserId");
            this.propertyTitleMap.put("modifyTime", "modifyTime");
        }
        return this.propertyTitleMap;
    }
}